/**
 * Copyright (c) qzsoft All rights reserved.
 *
 * qzsoft.cn
 *
 * 版权所有，侵权必究！
 */

package com.qzsoft.system.modules.permission.role.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qzsoft.system.modules.permission.group.dao.SysUserGroupDao;
import com.qzsoft.system.modules.permission.group.dto.SysGroupDTO;
import com.qzsoft.system.modules.permission.role.service.SysRoleUserService;

import com.qzsoft.system.modules.permission.roleclass.dto.SysRoleClassTreeDTO;
import com.qzsoft.system.modules.permission.roleclass.service.impl.SysRoleClassServiceImpl;
import com.qzsoft.system.repository.sys.dao.SysRoleDao;
import com.qzsoft.system.repository.sys.dao.SysRoleUserDao;
import com.qzsoft.system.repository.sys.entity.SysRoleEntity;
import com.qzsoft.system.repository.sys.entity.SysRoleUserEntity;
import com.qzsoft.jeemis.common.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色用户关系
 *
 * @author
 * @since 1.0.0
 */
@Service
public class SysRoleUserServiceImpl extends BaseService implements SysRoleUserService {

    @Autowired
    SysRoleUserDao sysRoleUserDao;
    @Autowired
    private SysRoleDao sysRoleDao;
    @Autowired
    private SysRoleClassServiceImpl sysRoleClassServiceImpl;
    @Autowired
    private SysUserGroupDao sysUserGroupDao;


    @Override
    public void saveOrUpdate(Long userId, List<Long> roleIdList) {
        //先删除角色用户关系
        deleteByUserIds(new Long[]{userId});

        // 判断要添加的数据是否为空
        if(null == roleIdList || 0 == roleIdList.size()) {
            return ;
        }

		List<Long> listAllDistinct = roleIdList.stream().distinct().collect(Collectors.toList());
        //保存角色用户关系
        for(Long roleId : listAllDistinct){
            SysRoleUserEntity sysRoleUserEntity = new SysRoleUserEntity();
            sysRoleUserEntity.setUserId(userId);
            sysRoleUserEntity.setRoleId(roleId);

            //保存
			sysRoleUserDao.insert(sysRoleUserEntity);
        }
    }

    @Override
    public void deleteByRoleIds(Long[] roleIds) {
		QueryWrapper<SysRoleUserEntity> queryWrapper=new QueryWrapper<>();
		queryWrapper.in("role_id",roleIds);
    	sysRoleUserDao.delete(queryWrapper);
    }

    @Override
    public void deleteByUserIds(Long[] userIds) {
		QueryWrapper<SysRoleUserEntity> queryWrapper=new QueryWrapper<>();
		queryWrapper.in("user_id",userIds);
		sysRoleUserDao.delete(queryWrapper);
    }

    @Override
    public List<Long> getRoleIdList(Long userId) {

		QueryWrapper<SysRoleUserEntity> queryWrapper=new QueryWrapper<>();
		queryWrapper.eq("user_id",userId).select("role_id");
		List<SysRoleUserEntity> roleList=sysRoleUserDao.selectList(queryWrapper);
        //移除null元素 解决 All elements are null引起的异常
		roleList.removeAll(Collections.singleton(null));
		if(roleList!=null&&!roleList.isEmpty()){
            List<Long> roleIdList= roleList.stream().map(obj->{return obj.getRoleId();}).collect(Collectors.toList());
            return roleIdList;
        }else{
		    return null;
        }

    }

    @Override
    public List<Long> getUserIdList(Long roleId) {
        QueryWrapper<SysRoleUserEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("role_id",roleId).select("user_id").eq("has_delete",0);
        List<SysRoleUserEntity> userList=sysRoleUserDao.selectList(queryWrapper);
        List<Long> userIdList= userList.stream().map(obj->{return obj.getUserId();}).collect(Collectors.toList());
        return userIdList;
    }

    @Override
    public List<SysRoleClassTreeDTO> getAllRoleList(Long id) {
        List<SysRoleClassTreeDTO> Alllist=new ArrayList<SysRoleClassTreeDTO>();
        // 用户的角色
        List<Long> roleids=getRoleIdList(id);
        //增加非空判断
        if(roleids!=null&&!roleids.isEmpty()){
            for(Long roleid:roleids){
                SysRoleClassTreeDTO userDto = sysUserGroupDao.selectRoleById(roleid);
                if(userDto!=null&&!"".equals(userDto)){
                    userDto.setType("0");
                    userDto.setHasGroup(false);
                    Alllist.add(userDto);
                }

            }
        }


        if(Alllist!=null&&Alllist.size()!=0){
            for(SysRoleClassTreeDTO role:Alllist){
                SysRoleEntity sysRoleEntity = sysRoleDao.selectById(role.getId());
                //判断是否是用户角色
                if(sysRoleEntity.getDeptId()!=null&&!"".equals(sysRoleEntity.getDeptId())){
                    role.setType("1");
                }
            }
        }


        //组织的默认角色
        //1 先查询用户绑定的机构
//        List<SysUserDeptDTO> sysUserDeptDTOList = sysUserDeptV2Service.getUserDeptList(id);
//        List<String> deptids=new ArrayList<>();
//        for(SysUserDeptDTO dept:sysUserDeptDTOList){
//            deptids.add(dept.getDeptId());
//        }
//        //2 查询用户机构的默认角色的机构  并将角色带出来
//        List<SysRoleClassTreeDTO> sysRoleGroupTreeV2DTOS1 = sysRoleGroupV2ServiceImpl.queryDefaultRolesBydeptIds(deptids);
//        Alllist.addAll(sysRoleGroupTreeV2DTOS1);

        //用户组的角色
        //1. 先查询用户的所在的用户组
        List<SysGroupDTO> groupList = sysUserGroupDao.getGroupList(id);
        List<String> groupids=new ArrayList<>();
        for(SysGroupDTO group:groupList){
            groupids.add(group.getId());
        }
        //2 查询用户组的默认角色  并将角色带出来
        List<SysRoleClassTreeDTO> SysRoleClassTreeDTOS2 = sysRoleClassServiceImpl.queryDefaultRolesByGroupIds(groupids);
        Alllist.addAll(SysRoleClassTreeDTOS2);

        return Alllist;
    }

}